<?php 
if(!defined('IN_OPEN')) exit('no access');
require_once OPEN_ROOT.'/lib/class/db.class.php';
require_once OPEN_ROOT.'/config.inc.php';
require_once OPEN_ROOT.'/api/include/class/httpsqs.class.php';
require_once OPEN_ROOT.'/lib/class/memcached.class.php';
class count
{
	public function __construct()
	{
		global $mem;
		if(empty($oauth_dbhost)) include  OPEN_ROOT.'/config.inc.php';
		$this->db = db::connect($oauth_dbhost,$oauth_dbuser,$oauth_dbpw,$oauth_dbname);
		if(empty($mem)) $mem = new Memcached();
		$this->mem = $mem;
		$this->httpsqs = new httpsqs();
		$this->sqshost = $sqshost;
		$this->sqsport = $sqsport;
	}
	public function updateUserAppData($tyid,$appid)
	{
		$data = array('tyid'=>$tyid,'appid'=>$appid);
		$data = json_encode($data);
		$result = $this->httpsqs->put($this->sqshost, $this->sqsport, 'utf-8', 'sqs_useraction', $data);
	  	//echo $result = $this->httpsqs->get($this->sqshost, $this->sqsport, 'utf-8', 'sqs_useraction');
		//echo $result = $this->httpsqs->status($this->sqshost, $this->sqsport, 'utf-8', 'sqs_useraction');
		//var_dump($result);
		if($result==false) return false;
		$cachekey = md5($tyid.$appid.'_useraction');
		$result = $this->mem->set($cachekey,1);
		return $result;
	}
	public function getUserAppFlag($tyid,$appid,$cacheflag=true)
	{
		
		//$tyid = intval($tyid);
		$daytime = date('Ymd');
		$cachekey = md5($tyid.$appid.$daytime.'_useraction');
		
		$data = $this->mem->get($cachekey);
		//echo "cache online<br>";
		///var_dump($data);
		//echo "cache online end<br>";
		if($data==false || $cacheflag==false)
		{
			$sql = "select tyid from tyopen_useraction where tyid=$tyid and appid=$appid and daytime=$daytime";
			$data = $this->db->fetchAll($sql);
			if($data==false) 	$data = 0;
			else $data = 1;
			$this->mem->set($cachekey,$data,172800);
			
		}
		return intval($data);
	}
	public function getapicount($appid,$apiname,$daytime,$cacheflag=true)
	{
		$cachekey = md5($appid.$apiname.'_apicount');
		$data = $this->mem->get($cachekey);
		if($data==false || $cacheflag==false)
		{
			$sql = "select count from tyopen_apicount where appid=$appid and apiname='$apiname' and daytime=$daytime";
			$data = $this->db->fetchOne($sql);
			if($data==false) return false;
			$data = intval($data['count']);
			$this->mem->set($cachekey,$data);
		}
		return $data;
	}
	public function updateapicount($appid,$apiname,$count)
	{
		$daytime = date('Ymd');
		$sql = "insert ignore into tyopen_apicount(appid,apiname,count,daytime) values($appid,'$apiname',1,$daytime) on duplicate key update count=count+$count";
		$result = $this->db->query($sql);
		if($result==false) return false;
		$cachekey = md5($appid.$apiname.'_apiaddcount');
		$this->mem->set($cachekey,0);
		return $result;
	}
	
	public function getAllUserAppData()
	{
		$sql = "select * from tyopen_useraction";
		return $result = $this->db->fetchAll($sql);
	}
}
?>